package com.tanhua.app.interceptor;

import cn.hutool.core.util.StrUtil;
import com.tanhua.app.service.UserService;
import com.tanhua.domain.db.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;


    // 拦截
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
      //  System.out.println(request.getRequestURL());

        // 1、通过请求头Authorization获取token
        String token = request.getHeader("Authorization");
        // 2、校验app端是否携带token
        if (StrUtil.isEmpty(token)) {
            response.setStatus(401); // 权限不足
            return false;
        }
        // 3、根据token获取user对象
        User user = userService.findUserByToken(token);
        if (user == null) {
            response.setStatus(401); // 权限不足
            return false;
        }

        // 4、存储到threadLocal
        UserHolder.set(user);
        // 5、放行
        return true;
    }

    // 响应时，清除线程绑定
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.remove();
    }
}
